const db = require('../model/db')

// 基类
class Base {
  constructor() {
    this.c_name = this.constructor.name.toLocaleLowerCase()
    this.TableName = `tk_${this.c_name}`
  }

  async baseFindAll(req, res) {
    const { title, page = 1, limit = 10 } = req.query
    const startIndex = (page - 1) * limit
    const app_id = req.headers.appid || 1
    const data = { total: 0, rows: {} }
    const sql1 = `select * from ${this.TableName} where app_id = ${app_id}`

    const [[rows]] = await db.query(sql1, [`%${title || ''}%`, startIndex, Number(limit)])

    if (rows) {
      data.rows = rows
    }

    return res.cc('success', 0, { data })
  }

  async baseFindOne({ req, res, where = 'id = ?' }) {
    const { id } = req.params
    const data = { total: 0, rows: '' }
    const sql = `select * from ${this.TableName} where ${where}`

    const [[rows]] = await db.query(sql, [id])

    if (rows) {
      data.rows = rows
      delete rows.password
    }

    return res.cc('success', 0, { data })
  }

  // 新增
  async baseCreate(req, res) {
    const sql = `insert into ${this.TableName} set ?`
    const app_id = req.headers.appid || 1

    req.body.app_id = app_id

    const [rows] = await db.query(sql, [req.body])

    if (!rows.affectedRows) {
      return res.cc('新增失败！')
    }

    return res.cc('success', 0)
  }

  async baseUpdate(req, res, key = 'id') {
    const { id } = req.params
    const app_id = req.headers.appid || 1
    const conditions = key === 'id' ? 'id=?' : 'app_id=?'
    const sql = `update ${this.TableName} set ? where ${conditions}`
    const value = id === 'id' ? id : app_id

    const [rows] = await db.query(sql, [req.body, value])

    if (!rows.affectedRows) {
      return res.cc('修改失败！')
    }

    return res.cc('success', 0)
  }

  handlerOptions(options, id) {
    const { key, value } = options
    let conditions = ''

    if (key === 'id') {
      conditions = `id in (${id})`
    } else {
      conditions = `${key} in (${value})`
    }

    return conditions
  }

  async baseRemove(req, res, options = { key: 'id', value: '' }) {
    const { id } = req.params
    const conditions = this.handlerOptions(options, id)

    const sql = `delete from ${this.TableName} where ${conditions}`

    const [rows] = await db.query(sql)

    if (!rows.affectedRows) {
      return res.cc('删除失败！')
    }

    return res.cc('success', 0)
  }

  getModelName() {
    console.log('1modelName', this.constructor.name)
  }
}

module.exports = Base
